package game.leon.war.game;

import game.leon.engine.net.GameMessageHandler;
import game.leon.engine.net.GameSession;
import game.leon.engine.net.codec.GameRawMessage;
import game.leon.engine.utils.Reciever;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * User: bianpeng
 * Date: 12-1-11
 */
@Component
public class GameReciever implements GameMessageHandler {
    private Logger logger = Logger.getLogger(getClass());
    private Reciever<GameMessage> reciever = new Reciever<GameMessage>();
    @Autowired
    private GameConsumer gameConsumer;
    @PostConstruct
    public void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(;;) {
                    if (reciever.isEmpty()) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            logger.error("sleep failed", e);
                        }
                    } else {
                        gameConsumer.consume(reciever.consume());
                    }
                }
            }
        }).start();
    }
    @Override
    public void execute(GameSession session, GameRawMessage message) {
        reciever.recieve(new GameMessage(session, message));
    }
}
